package com.academy.teacher;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;

import com.academy.querystapp.R;
import com.academy.services.RequestMethod;
import com.academy.services.RestClient;

public class TeacherRegistration extends Activity implements OnClickListener
{
	
	EditText edtName,edtCollegeName,edtQual,edtMobileNo,edtEmailID,edtPassword,edtConfirmPassword,edtDesignation;
	Button btnRegistration,btnClear;
	String strName,strCollegeName,strQualification,strDesignation,strMobileNo,strEmailID,strPassword,strConfirmPassword;
	
	Boolean errorStatus=true;
	RestClient restRequest;
	Boolean value=true;
	ProgressDialog progress_Dialog;
	Boolean isProcessCompleted = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		// TODO Auto-generated method stub
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.teacher_registration);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		initialzeView();
		
	}
	
	public void initialzeView()
	{
		edtName=(EditText) findViewById(R.id.edtName);
		edtCollegeName=(EditText) findViewById(R.id.edtCollegeName);
		edtQual=(EditText) findViewById(R.id.edtQualification);
		edtMobileNo=(EditText) findViewById(R.id.edtMobileNo);
		edtEmailID=(EditText) findViewById(R.id.edtEmailID);
		edtPassword=(EditText)findViewById(R.id.edtPassword);
		edtConfirmPassword=(EditText) findViewById(R.id.edtConfirmPassword);
		edtDesignation=(EditText) findViewById(R.id.edtDesignation);
		
		btnRegistration=(Button) findViewById(R.id.btnRegistration);
		btnClear=(Button) findViewById(R.id.btnClear);
		
		btnRegistration.setOnClickListener(this);
		btnClear.setOnClickListener(this);
		
	}

	@Override
	public void onClick(View v) 
	{
	
		if(v==btnRegistration)
		{
			strName=edtName.getText().toString().trim();
			strCollegeName=edtCollegeName.getText().toString().trim();
			strQualification=edtQual.getText().toString().trim();
			strDesignation=edtDesignation.getText().toString().trim();
			strEmailID=edtEmailID.getText().toString().trim();
			strMobileNo=edtMobileNo.getText().toString().trim();
			strPassword=edtPassword.getText().toString().trim();
			strConfirmPassword=edtConfirmPassword.getText().toString().trim();
			
			if(strName.equals("")&& strEmailID.equals("")&& strMobileNo.equals("")&& strPassword.equals("")&& strConfirmPassword.equals(""))
			{
				errorStatus=false;
				Builder builder = new Builder(this);
				builder.setTitle("Registration");
				builder.setMessage("Please Enter all the Values!");
				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int arg1)
					{	
						dialog.dismiss();
					}
				});
				AlertDialog alertDialog = builder.create();
				alertDialog.show();
			}
			else if(strName.equals(""))
			{
				errorStatus=false;
				Builder builder = new Builder(this);
				builder.setTitle("Registration");
				builder.setMessage("Enter Your Name !");
				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int arg1)
					{	
						dialog.dismiss();
					}
				});
				AlertDialog alertDialog = builder.create();
				alertDialog.show();
			}	
			else if(strDesignation.equals(""))
			{
				errorStatus=false;
				Builder builder = new Builder(this);
				builder.setTitle("Registration");
				builder.setMessage("Enter Your Designation !");
				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int arg1)
					{	
						dialog.dismiss();
					}
				});
				AlertDialog alertDialog = builder.create();
				alertDialog.show();
			}
//			else if(strName.length()<5 ||strName.length()>10)
//			{
//				errorStatus=false;
//				Builder builder = new Builder(this);
//				builder.setTitle("Registration");
//				builder.setMessage("Enter between 5 to 10 characters your name !");
//				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
//				{
//					public void onClick(DialogInterface dialog, int arg1)
//					{	
//						dialog.dismiss();
//					}
//				});
//				AlertDialog alertDialog = builder.create();
//				alertDialog.show();
//			}
			else if(strEmailID.equals(""))
			{
				errorStatus=false;
				Builder builder = new Builder(this);
				builder.setTitle("Registration");
				builder.setMessage("Enter your Email ID !");
				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int arg1)
					{	
						dialog.dismiss();
					}
				});
				AlertDialog alertDialog = builder.create();
				alertDialog.show();
			}
			else if(!validateMailId(edtEmailID.getText().toString()))
			{
				errorStatus=false;
				Builder builder = new Builder(this);
				builder.setTitle("Registration");
				builder.setMessage("Enter Valid Email-ID!");
				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int arg1)
					{	
						dialog.dismiss();
					}
				});
				AlertDialog alertDialog = builder.create();
				alertDialog.show();
			}
			else if(strMobileNo.equals(""))
			{
				errorStatus=false;
				Builder builder = new Builder(this);
				builder.setTitle("Registration");
				builder.setMessage("Enter your mobile number !");
				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int arg1)
					{	
						dialog.dismiss();
					}
				});
				AlertDialog alertDialog = builder.create();
				alertDialog.show();
			}
//			else if(strPhoneNo.length()<10||strPhoneNo.length()>10)
//			{
//				errorStatus=false;
//				Builder builder = new Builder(this);
//				builder.setTitle("Registration");
//				builder.setMessage("Enter your only 10 digits mobile number !");
//				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
//				{
//					public void onClick(DialogInterface dialog, int arg1)
//					{	
//						dialog.dismiss();
//					}
//				});
//				AlertDialog alertDialog = builder.create();
//				alertDialog.show();
//			}
			else if(strPassword.equals(""))
			{
				errorStatus=false;
				Builder builder = new Builder(this);
				builder.setTitle("Registration");
				builder.setMessage("Enter your password !");
				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int arg1)
					{	
						dialog.dismiss();
					}
				});
				AlertDialog alertDialog = builder.create();
				alertDialog.show();
			}
			else if(strConfirmPassword.equals(""))
			{
				errorStatus=false;
				Builder builder = new Builder(this);
				builder.setTitle("Registration");
				builder.setMessage("Enter confirm password !");
				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int arg1)
					{	
						dialog.dismiss();
					}
				});
				AlertDialog alertDialog = builder.create();
				alertDialog.show();
			}
//			else if(strPassword.length()<6 || strPassword.length()>8)
//			{
//				errorStatus=false;
//				Builder builder = new Builder(this);
//				builder.setTitle("Registration");
//				builder.setMessage("Enter between 6 to 8 characters your password !");
//				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
//				{
//					public void onClick(DialogInterface dialog, int arg1)
//					{	
//						dialog.dismiss();
//					}
//				});
//				AlertDialog alertDialog = builder.create();
//				alertDialog.show();
//			}
			else if(!strConfirmPassword.equals(strPassword))
			{
				errorStatus=false;
				Builder builder = new Builder(this);
				builder.setTitle("Registration");
				builder.setMessage("Confirm Password Mismatch !");
				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int arg1)
					{	
						dialog.dismiss();
					}
				});
				AlertDialog alertDialog = builder.create();
				alertDialog.show();
			}	
			else 
			{
				errorStatus=true;
				isProcessCompleted = false;
				progress_Dialog = ProgressDialog.show(TeacherRegistration.this, "","Please Wait ...", true);
				AsyncTask<Void, Void, Boolean> waitForCompletion = new AsyncTask<Void, Void, Boolean>()
				{	
					protected Boolean doInBackground(Void... params)
					{
						while(isProcessCompleted == false)
						{	                      
							System.out.println("Login testdialog.......");
							try 
							{
								  isProcessCompleted = true;
								  restRequest = new RestClient(getString(R.string.addTeacherURL));
								  restRequest.AddParam(getString(R.string.teacherName_param), edtName.getText().toString().trim());
								  restRequest.AddParam(getString(R.string.teacherCollege_param), edtCollegeName.getText().toString().trim());
								  restRequest.AddParam(getString(R.string.teacherQualification_param), edtQual.getText().toString().trim());
								  restRequest.AddParam(getString(R.string.teacherdesignation_param), edtDesignation.getText().toString().trim());
								  restRequest.AddParam(getString(R.string.MobileNo_param), edtMobileNo.getText().toString().trim());
								  restRequest.AddParam(getString(R.string.EmailID_param), edtEmailID.getText().toString().trim());
								  restRequest.AddParam(getString(R.string.password_param), edtPassword.getText().toString().trim());
								  restRequest.AddParam(getString(R.string.userType_Param),"AddTeacher");
						        try
						        {
						        	restRequest.Execute(RequestMethod.GET);
						        }
						        catch(Exception e)
						        {
						      	  System.out.println("Error in the execution"+e.toString());
						        }
						      
						        Thread.sleep(100);
								}
								catch (InterruptedException e)
								{
	                          
								}
						}
						
						return true;
					};
				
					protected void onPostExecute(Boolean result) 
					{
						progress_Dialog.dismiss();
						if(result == true)
						{  
							 parseResponse(restRequest.getResponse());
            	  	  	}
						else
						{
               
						}
					}
				};
				waitForCompletion.execute(null, null, null);		
			}
			
	
		}
		
		if(v==btnClear)
		{
			clear();
		}
	}
	
	private boolean validateMailId(String inputEmail)
	{
		 String regExpn= ".+@.+\\.[a-z]+";
		 Pattern patternObj = Pattern.compile(regExpn);
		 Matcher matcherObj = patternObj.matcher(inputEmail);
		 if (matcherObj.matches())
		 {
			 	return true;
		 }
		 else
		 {
			 	return false;
		 }
	 }
	
	public void clear()
	{
		edtName.setText("");
		edtCollegeName.setText("");
		edtQual.setText("");
		edtDesignation.setText("");
		edtEmailID.setText("");
		edtMobileNo.setText("");
		edtPassword.setText("");
		edtConfirmPassword.setText("");			
		
	}
	
	private void parseResponse(String response)
	{
		if(response==null ||response.equals("null"))
		{
			Builder builder = new Builder(this);
			builder.setMessage("No Server Found!");
			builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
			{
				public void onClick(DialogInterface dialog, int arg1)
				{	
					dialog.dismiss();
				}
			});
			AlertDialog alertDialog = builder.create();
			alertDialog.show();
		}
		else
		{
			try 
			{ 
			
				JSONObject RootObject = new JSONObject(response);
				System.out.println("JSON Object "+RootObject.toString());
				JSONObject queryResultObject = RootObject.getJSONObject("queryResult");
				System.out.println("queryResultObject "+queryResultObject.toString());
				
				System.out.println("Response "+queryResultObject.getString("status"));
				System.out.println("Value of response"+response);
				
				if(queryResultObject.getString("status").equals("false"))
				{
					Builder builder = new Builder(this);
					builder.setTitle("Registration");
					builder.setMessage(queryResultObject.getString("description"));
					builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
					{
						public void onClick(DialogInterface dialog, int arg1)
						{		
//							edtName.setText("");
//							edtCollegeName.setText("");
//							edtQual.setText("");
//							edtEmailID.setText("");
							edtMobileNo.setText("");
//							edtPassword.setText("");
//							edtConfirmPassword.setText("");			
							dialog.dismiss();
						}
					});
					AlertDialog alertDialog = builder.create();
					alertDialog.show();	 
				}
				else if(queryResultObject.getString("status").equals("true"))
				{
					Builder builder = new Builder(this);
					builder.setTitle(queryResultObject.getString("description"));
					builder.setPositiveButton("Login", new DialogInterface.OnClickListener()
					{
						public void onClick(DialogInterface dialog, int arg1)
						{	
							Intent i=new Intent(TeacherRegistration.this,TeacherActivty.class);
							startActivity(i);
							finish();
						}
					});
					builder.setNegativeButton("Exit", new DialogInterface.OnClickListener()
					{
						public void onClick(DialogInterface dialog, int arg1)
						{	
							Intent intent = new Intent(Intent.ACTION_MAIN);
		    	   			intent.addCategory(Intent.CATEGORY_HOME);
		    	   			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		    	   			startActivity(intent);	    	   		
		    	   			finish();
						}
					});
					AlertDialog alertDialog = builder.create();
					alertDialog.show();				
				}
		  }
		  catch (JSONException e) 
		  {
			  e.printStackTrace();
		  } 
		}
	}
	
	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {

	    View v = getCurrentFocus();
	    boolean ret = super.dispatchTouchEvent(event);

	    if (v instanceof EditText) {
	        View w = getCurrentFocus();
	        int scrcoords[] = new int[2];
	        w.getLocationOnScreen(scrcoords);
	        float x = event.getRawX() + w.getLeft() - scrcoords[0];
	        float y = event.getRawY() + w.getTop() - scrcoords[1];

	        Log.d("Activity", "Touch event "+event.getRawX()+","+event.getRawY()+" "+x+","+y+" rect "+w.getLeft()+","+w.getTop()+","+w.getRight()+","+w.getBottom()+" coords "+scrcoords[0]+","+scrcoords[1]);
	        if (event.getAction() == MotionEvent.ACTION_UP && (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w.getBottom()) ) { 

	            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
	            imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
	        }
	    }
	return ret;
	}

	
//	public void onBackPressed() 
//	{
//	   Intent back=new Intent(getApplicationContext(),TeacherActivty.class);
//	   startActivity(back);
//	   this.finish();
//	}

}
